import * as pathToRegexp from "path-to-regexp";
import _ from "lodash";
import axios from "axios";
import { Notification } from "@arco-design/web-vue";
// import { baseURL } from "@/utils/config"
const baseURL = import.meta.env.VITE_RES_URL;

export async function request(name, options) {
  const {
    method = "get",
    data,
    params,
    headers,
    cancelToken,
    responseType,
  } = options;
  let url = options.url;
  if (!_.startsWith(url, "http")) {
    url = baseURL + url;
  }
  // 跨域设置
  const withCredentials = true;
  const cloneParams = _.cloneDeep(params);

  // use(两个参数)
  axios.interceptors.request.use(
    (req) => {
      // 在发送请求前要做的事儿
      //   req.headers["USER_LOGIN_TOKEN"] = localStorage.getItem("token");
      return req;
    },
    (err) => {
      // 在请求错误时要做的事儿
      // 该返回的数据则是axios.catch(err)中接收的数据
      return Promise.reject(err);
    }
  );

  //响应拦截器
  axios.interceptors.response.use(
    (res) => {
      //   if (res.config.url.indexOf("/login") > -1) {
      //     localStorage.setItem("token", res.headers.user_login_token);
      //   }
      return res;
    },
    (err) => {
      Notification.error({
        title: "提示",
        content: err.response.data.msg,
      });
      return err;
    }
  );

  // 解析URl并将data中的数据填充到URL中
  try {
    const domainReg = new RegExp(/[a-zA-Z]+:\/\/[^/]*/);
    let domain = "";
    if (domainReg.test(url)) {
      domain = domainReg.exec(url)?.[0] || "";
      url = url.slice(domain.length);
    }

    const match = pathToRegexp.parse(url);
    params && (url = pathToRegexp.compile(url)(params));
    for (const item of match) {
      item instanceof Object &&
        cloneParams &&
        item.name in cloneParams &&
        delete cloneParams[item.name];
    }
    url = domain + url;
  } catch (e) {
    console.log(url, "请求参数错误：", e.message);
  }

  const realOptions = {
    method,
    url,
    params: cloneParams,
    data,
    withCredentials,
    responseType,
  };

  if (cancelToken) {
    realOptions.cancelToken = cancelToken;
  }

  const jsonHeader = {
    "Content-Type": "application/json",
  };
  realOptions.headers = _.merge(jsonHeader, headers);
  try {
    const res = await axios(realOptions);
    if (res.status !== 200) {
      throw new Error(res.response.data);
    }
    if (res.data.code === "500") {
      Notification.error({
        title: "提示",
        content: res.data.msg,
      });
    }
    return res.data;
  } catch (error) {
    return error;
  }
}

/**
 * 执行 post 请求
 * @param url
 * @param params
 */
export const post = async (url, data) => {
  try {
    const res = await axios.post(url, data);
    return res.data;
  } catch (error) {
    Notification.error({
      title: "请求错误",
      content: error.response.data.message,
    });
    console.log(`post ${url}`, error);
    return error.response.data;
  }
};

/**
 * 执行 get 请求
 * @param url
 * @param params
 */

export const get = async (url, params) => {
  try {
    const res = await axios.get(url, {
      params,
    });
    return res.data;
  } catch (error) {
    console.log(`get ${url}`, error);
    return error.response.data.data;
  }
};
